package ru.ifmo.tanya.service.impl;

import ru.ifmo.tanya.core.huntgroups.HuntGroup;
import ru.ifmo.tanya.core.users.User;
import ru.ifmo.tanya.core.users.UserKeeper;
import ru.ifmo.tanya.core.users.UserRole;
import ru.ifmo.tanya.db.HuntGroupManager;
import ru.ifmo.tanya.keepers.OnlineUsersKeeper;
import ru.ifmo.tanya.keepers.UserStatusKeeper;
import ru.ifmo.tanya.service.HttpService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;


public class LoginService implements HttpService {

    private UserKeeper userKeeper = new UserKeeper();
    private HuntGroupManager huntGroupManager = new HuntGroupManager();
    private UserStatusKeeper userStatusKeeper = new UserStatusKeeper();
    private final Random random = new Random();

    @Override
    public void invoke(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = userKeeper.checkPasswordAndSetCookie(request, response);
        HuntGroup defaultHuntGroup = huntGroupManager.getHuntGroupById(1 + random.nextInt(3));     // comment
        if (user != null) {
//            userStatusKeeper.addGroupToUser(user, defaultHuntGroup);           // comment
            new OnlineUsersKeeper().userCame(user);
            if (user.getRole() == UserRole.AGENT) {
                response.sendRedirect("/service/show/hunt/groups");
            } else {
                response.sendRedirect("/service/agents/and/queues");
            }
        } else {
            response.sendRedirect("/");
        }
    }
}
